<template>
  <div></div>
</template>

<script setup>
import { setLineStyle } from "@/api/ol-api/index.js";
import { getCurrentInstance, onMounted, watch } from "vue";
import Query from "@/api/mapgis-api/Query.js";

const { proxy } = getCurrentInstance();
const service = {
  name: "xm",
  layerId: [1], // Number|Array
  crossOrigin: 'Anonymous'
};
/* 单独读取id为1的图层 */
let trafficSource = null;
let trafficLayer = null;
const props = defineProps({
  showTrafficLayer: Boolean,
});

watch(
  () => props.showTrafficLayer,
  (isTrafficVisible) => {

    if (isTrafficVisible) {
      loadTrafficData();
    } else {
      clearTrafficData();
    }
  }
);

onMounted(() => {
  initializeTrafficLayer();
});

function initializeTrafficLayer() {
  trafficSource = new ol.source.Vector({});
  trafficLayer = new ol.layer.Vector({
    source: trafficSource,
  });
}

async function loadTrafficData() {
  const trafficData = await Query.queryByLayerId({ service });
  applyTrafficStyles(trafficData);

}

function clearTrafficData() {
  if (trafficSource) {
    trafficSource.clear();
  }
  if (proxy.$map && trafficLayer) {
    proxy.$map.removeLayer(trafficLayer);
  }
}

function applyTrafficStyles(features) {
  if (trafficSource) {
    trafficSource.addFeatures(features);
  }
  if (proxy.$map && trafficLayer) {
    proxy.$map.addLayer(trafficLayer);
  }

  const lowTrafficFlow = features.filter(
    (item) => item.values_.values_.车流量 < 1000
  );
  lowTrafficFlow.forEach((feature) =>
    feature.setStyle(setLineStyle({ color: "rgb(34,139,34)" }))
  );

  const mediumTrafficFlow = features.filter(
    (item) =>
      item.values_.values_.车流量 >= 1000 && item.values_.values_.车流量 < 1500
  );
  mediumTrafficFlow.forEach((feature) =>
    feature.setStyle(setLineStyle({ color: "rgb(255,127,36)" }))
  );

  const highTrafficFlow = features.filter(
    (item) => item.values_.values_.车流量 >= 1500
  );
  highTrafficFlow.forEach((feature) =>
    feature.setStyle(setLineStyle({ color: "rgb(178,34,34)" }))
  );
}
</script>